﻿using Microsoft.AspNet.SignalR.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SignalrSLClient
{
    public partial class MainPage : UserControl
    {
        //http post sample
        //    String email = Email.Text;
        //    String password = Password.Password;
        //    String data = "email=" + email + "&password=" + password;
        //    WebClient wc = new WebClient();
        //    Uri uri = new Uri("http://api.server.com/login");
        //    wc.UploadStringCompleted += new ploadStringCompletedEventHandler(wc_UploadStringCompleted);
        //    wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
        //wc.Encoding = Encoding.UTF8;
        //wc.UploadStringAsync(uri, "POST", data);


        public String UserName { get; set; }
        public IHubProxy HubProxy { get; set; }
        const string ServerURI = "http://localhost:8080/signalr";
        public HubConnection Connection { get; set; }
        public MainPage()
        {
            InitializeComponent();
            if (!App.Current.IsRunningOutOfBrowser)
                App.Current.Exit += Current_Exit;
        }

        void Current_Exit(object sender, EventArgs e)
        {
            if (Connection != null)
            {
                Connection.Stop();
                Connection.Dispose();
            }
        }

        private void ButtonSend_Click(object sender, RoutedEventArgs e)
        {
            HubProxy.Invoke("Send", UserName, TextBoxMessage.Text);
            TextBoxMessage.Text = String.Empty;
            TextBoxMessage.Focus();
        }

        void Connection_Closed()
        {
            //Hide chat UI; show login UI
            //var dispatcher = Application.Current.Dispatcher;
            this.Dispatcher.BeginInvoke(() => ChatPanel.Visibility = Visibility.Collapsed);
            this.Dispatcher.BeginInvoke(() => ButtonSend.IsEnabled = false);
            this.Dispatcher.BeginInvoke(() => StatusText.Text = "You have been disconnected.");
            this.Dispatcher.BeginInvoke(() => SignInPanel.Visibility = Visibility.Visible);
        }

        private void SignInButton_Click(object sender, RoutedEventArgs e)
        {
            UserName = UserNameTextBox.Text;
            //Connect to server (use async method to avoid blocking UI thread)
            if (!String.IsNullOrEmpty(UserName))
            {
                StatusText.Visibility = Visibility.Visible;
                StatusText.Text = "Connecting to server...";
                ConnectAsync();
            }
        }

        /// <summary>
        /// Creates and connects the hub connection and hub proxy. This method
        /// is called asynchronously from SignInButton_Click.
        /// </summary>
        private async void ConnectAsync()
        {
            Connection = new HubConnection(ServerURI);
            Connection.Closed += Connection_Closed;
            HubProxy = Connection.CreateHubProxy("MyHub");
            //Handle incoming event from server: use Invoke to write to console from SignalR's thread
            HubProxy.On<string, string>("AddMessage", (name, message) =>
                this.Dispatcher.BeginInvoke(() =>
                    lb_msg.Items.Insert(0,String.Format("{0}: {1}\r", name, message))
                )
            );
            try
            {
               await Connection.Start();
            }
            catch (HttpRequestException)
            {
                StatusText.Text = "Unable to connect to server: Start server before connecting clients.";
                //No connection: Don't enable Send button or show chat UI
                return;
            }

            //Show chat UI; hide login UI
            SignInPanel.Visibility = Visibility.Collapsed;
            ChatPanel.Visibility = Visibility.Visible;
            ButtonSend.IsEnabled = true;
            TextBoxMessage.Focus();
            lb_msg.Items.Insert(0, "Connected to server at " + ServerURI + "\r");
        }

    }
}
